// shop/car/index.js
var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    stepper:1,
    goodsData:[],//商品数据
    projectData:[],//项目数据
    money:0,//总价
    goodsMoney:0,//商品价格
    projectMoney:0,//项目价格
    show:false,//删除弹出层
    checkedAll:false,//全选
    allGroup:[],
    listData:[],//列表数据
    userId:wx.getStorageSync('userId'),//会员id
    checkedProjectData:[],
    checkedGoodsData:[],
    show5:false,
    show6:false,
    pageNo:1,
    state: wx.getStorageSync('state'),
    states: false,
    btnState:false,
    bgcolor: home.getKey('bgcolor'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      states:false,
      state: wx.getStorageSync('state'),
    });
  },

  //获取购物车项目列表
  getProjectCar(){
    let that = this;
    wx.request({
      url: url + 'shopprojectcart/ShopProjectCart/list',
      data:{
        memberId:that.data.userId,
        storeId:home.getKey('storeId'),
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          if (res.data.result.length == 0 && that.data.goodsData.length == 0) {
            that.setData({show5:true});
          } else {
            for (let i = 0; i < res.data.result.length; i++) {
              res.data.result[i].commodityPic = 'https://kyz.fbhkj.com//'+res.data.result[i].commodityPic;
            }
            that.setData({
              projectData:res.data.result,
              show5:false
            });
          }
          let money = 0;
          let allGroup = [];
          let goodsData = that.data.goodsData;
          let projectData = that.data.projectData;
          let goodsMoney = 0;
          let projectMoney = 0;
          for (let i = 0; i < goodsData.length; i++) {
            money += goodsData[i].qty * goodsData[i].price;
            allGroup.push(goodsData[i].id.toString());
            goodsMoney += goodsData[i].qty * goodsData[i].price;
          }
          for (let i = 0; i < projectData.length; i++) {
            money += projectData[i].qty * projectData[i].price;
            allGroup.push(projectData[i].id.toString());
            projectMoney += projectData[i].qty * projectData[i].price;
          }
          that.setData({
            allGroup:allGroup,
            money:money,
            goodsMoney:goodsMoney,
            projectMoney:projectMoney,
            checkedAll:true,
            checkedProjectData:projectData,
            checkedGoodsData:goodsData,
          })
        } else {
          home.wxMessage(res.data.message,'none');
          that.setData({show5:true});
        }
      }
    })
  },

  //获取购物车商品列表
  getCommodityCar(){
    let that = this;
    wx.request({
      url: url + 'shopcommoditycart/ShopCommodityCart/list',
      data:{
        memberId:that.data.userId,
        storeId:home.getKey('storeId'),
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.result.length; i++) {
            if (res.data.result[i].commodityPic) {
              let arr = res.data.result[i].commodityPic.split(',');
              res.data.result[i].commodityPic = 'https://kyz.fbhkj.com//'+arr[0];
            }
          }
          that.setData({
            goodsData:res.data.result,
          });
          
          that.setData({show5:false});
          that.getProjectCar();
        } else {
          home.wxMessage(res.data.message,'none');
          that.setData({show5:true});
        }
      }
    })
  },

  //全选
  onAllChange(e){
    let goodsData = this.data.goodsData;
    let projectData = this.data.projectData;
    let allGroup = [];
    let goodsMoney = 0;
    let projectMoney = 0;
    let checkedGoodsData = [];
    let checkedProjectData = [];
    if (e.detail) {
      for (let i = 0; i < goodsData.length; i++) {
        allGroup.push(goodsData[i].id.toString());   
        goodsMoney += goodsData[i].qty * goodsData[i].price;   
        checkedGoodsData.push(goodsData[i]);
      }
      for (let i = 0; i < projectData.length; i++) {
        allGroup.push(projectData[i].id.toString());    
        projectMoney += projectData[i].qty * projectData[i].price;
        checkedProjectData.push(projectData[i]);
      }
    } else {
      checkedGoodsData = [];
      checkedProjectData = [];
    }
    this.setData({
      checkedAll:e.detail,
      allGroup:allGroup,
      goodsMoney:goodsMoney,
      projectMoney:projectMoney,
      checkedGoodsData:checkedGoodsData,
      checkedProjectData:checkedProjectData
    });
    this.countMoney();
  },

  //商品全选
  onGoodsGroup(e){
    let len1 = this.data.projectData.length;
    let len2 = this.data.goodsData.length;
    let len = len1 + len2;
    let length = e.detail.length;
    let goodsData = this.data.goodsData;
    let checkedAll = false;
    if (len == length) {
      checkedAll = true;
    }
    let goodsMoney = 0;
    let checkedGoodsData = [];
    for (let i = 0; i < goodsData.length; i++) {
      let state = e.detail.indexOf(goodsData[i].id);
      if (state > -1) {
        goodsMoney += goodsData[i].qty * goodsData[i].price;
        checkedGoodsData.push(goodsData[i]);
      }
    }
    this.setData({
      allGroup:e.detail,
      checkedAll:checkedAll,
      goodsMoney:goodsMoney,
      checkedGoodsData:checkedGoodsData
    });
    this.countMoney();
  },

  //项目全选
  onProjectGroup(e){
    let len1 = this.data.projectData.length;
    let len2 = this.data.goodsData.length;
    let len = len1 + len2;
    let length = e.detail.length;
    let projectData = this.data.projectData;
    let checkedAll = false;
    if (len == length) {
      checkedAll = true;
    }
    let projectMoney = 0;
    let checkedProjectData = [];
    for (let i = 0; i < projectData.length; i++) {
      let state = e.detail.indexOf(projectData[i].id.toString());
      if (state > -1) {
        projectMoney += projectData[i].qty * projectData[i].price;
        checkedProjectData.push(projectData[i]);
      }
    }

    this.setData({
      allGroup:e.detail,
      checkedAll:checkedAll,
      projectMoney:projectMoney,
      checkedProjectData:checkedProjectData
    });
    this.countMoney();
  },

  //计算价格
  countMoney(){
    let goodsMoney = this.data.goodsMoney;
    let projectMoney = this.data.projectMoney;
    let money = (goodsMoney + projectMoney).toFixed(2);
    this.setData({
      money:money
    })
  },

  /**
   * 商品步进器
   */
  onGoodsStepper(e){
    let goodsData = this.data.goodsData;
    let goodsMoney = this.data.goodsMoney;
    let goodsId = e.currentTarget.dataset.id;
    let allGroup = this.data.allGroup;
    let state = allGroup.indexOf(goodsId.toString());
    let state1 = false;
    for (let i = 0; i < goodsData.length; i++) {
      if (goodsData[i].id == goodsId) {
        if (e.detail > goodsData[i].inventory) {
          state1 = true;
          e.detail = goodsData[i].inventory;
        }
        goodsMoney += (e.detail - goodsData[i].qty) * goodsData[i].price;
        if (e.detail <= 0) {
          e.detail = 0;
        }
        goodsData[i].qty = e.detail;
        if (e.detail == 0) {
          let ids = goodsId;
          let requestUrl = url + 'shopcommoditycart/ShopCommodityCart/deleteBatch?ids='+ids;
          this.deleteCar(requestUrl,ids);
          goodsData.splice(i,1);
        }
      }
    }

    if (state1) {
      home.wxMessage('库存不足','none');
    }

    let show5 = false;
    if (goodsData.length == 0) {
      show5 = true;
    }

    if (state > -1) {
      this.setData({
        goodsMoney:goodsMoney,
      });
    }
    this.setData({
      goodsData:goodsData,
      show5:show5
    });
    this.countMoney();
    this.editNum(1,e.detail,goodsId);
  },

  //修改数量
  editNum(type = 1,num,id){
    let that = this;
    let requestUrl = '';
    if (type == 1) {
      requestUrl = url + 'shopcommoditycart/ShopCommodityCart/updateQty';
    } else {
      requestUrl = url + 'shopprojectcart/ShopProjectCart/updateQty';
    }
    wx.request({
      url: requestUrl,
      data:{
        qty:num,
        id:id,
      },
      method: 'PUT',
      header: {
          "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          that.setData({
            goodsData:[],
            projectData:[],
            listData:[],
            allGroup:[],
          })
          that.getCommodityCar();
        } else {
          home.wxMessage('编辑失败,请稍后再试','none')
        }
      }
    })
  },

  /**
   * 项目步进器
   */
  onProjectStepper(e){
    let projectData = this.data.projectData;
    let projectMoney = this.data.projectMoney;
    let projectId = e.currentTarget.dataset.id;
    let allGroup = this.data.allGroup;
    let state = allGroup.indexOf(projectId.toString());
    for (let i = 0; i < projectData.length; i++) {
      if (projectData[i].id == projectId) {
        projectMoney += (e.detail - projectData[i].qty) * projectData[i].price;
        if (e.detail <= 0) {
          e.detail = 0;
        }
        projectData[i].qty = e.detail;
        if (e.detail == 0) {
          let ids = projectId;
          let requestUrl = url + 'shopprojectcart/ShopProjectCart/deleteBatch?ids='+ids;
          this.deleteCar(requestUrl,ids);
          projectData.splice(i,1);
        }
      }
    }

    if (state > -1) {
      this.setData({
        projectMoney:projectMoney,
      });
    }
    this.setData({
      projectData:projectData
    });
    this.countMoney();
    this.editNum(2,e.detail,projectId);
  },

  //跳转订单结算
  js(e){
    if (this.data.memberId == '') {
      return false;
    }
    if (this.data.allGroup.length == 0) {
      wx.showToast({
        title: '请选择订单',
        icon:'none'
      });
      return false;
    }
    let data = [];
    let checkedGoodsData = this.data.checkedGoodsData;
    let checkedProjectData = this.data.checkedProjectData;
    for (let i = 0; i < checkedGoodsData.length; i++) {
      checkedGoodsData[i].type = 1;
      data.push(checkedGoodsData[i]);
    }
    for (let i = 0; i < checkedProjectData.length; i++) {
      checkedProjectData[i].type = 2;
      data.push(checkedProjectData[i]);
    }
    data = JSON.stringify(data);
    wx.navigateTo({
      url: '../../user/order/info?data='+data,
    });
  },
  
  showPopup() {
    if (this.data.allGroup.length == 0) {
      wx.showToast({
        title: '请选择要删除的订单',
        icon:'none'
      });
      return false;
    }
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  //删除购物车
  del(e){
    let allGroup = this.data.allGroup;
    let goodsData = this.data.goodsData;
    let projectData = this.data.projectData;
    let ids1 = [];
    let ids2 = [];
    for (let i = 0; i < goodsData.length; i++) {
      let index = allGroup.indexOf(goodsData[i].id);
      if (index > -1) {
        ids1.push(goodsData[i].id);
      }      
    }
    for (let i = 0; i < projectData.length; i++) {
      let index = allGroup.indexOf(projectData[i].id);
      if (index > -1) {
        ids2.push(projectData[i].id);
      }      
    }
    let requestUrl = '';
    if (ids1.length > 0) {
      ids1 = ids1.toString();
      requestUrl += url + 'shopcommoditycart/ShopCommodityCart/deleteBatch?ids='+ids1;
      this.deleteCar(requestUrl,ids1);
    }
    if (ids2.length > 0) {
      ids2 = ids2.toString();
      requestUrl = url + 'shopprojectcart/ShopProjectCart/deleteBatch?ids='+ids2;
      this.deleteCar(requestUrl,ids1);
    }
  },

  deleteCar(requestUrl,ids){
    let that = this;
    let allGroup = this.data.allGroup;
    wx.request({
      url: requestUrl,
      data:{
        ids:ids,
      },
      method: 'DELETE',
      header: {
          "content-type": "application/json", // 默认
      },
      success:function (res) {
        let msg = '';
        let icon = '';
        if (res.data.code == 200) {
          msg = '成功删除';
          icon = 'success';
          ids = ids.split(',');
          for (let i = 0; i < ids.length; i++) {
            let index = allGroup.indexOf(ids[i].id);
            allGroup.splice(index,1);
          }
          that.setData({allGroup:allGroup,money:0,checkedAll:false});
        } else {
          msg = '删除失败';
          icon = 'none';
        }
        home.wxMessage(msg,icon);
        that.getCommodityCar();
        that.setData({ show: false });
      }
    })
  },
  //小程序授权
  login() {
    wx.showLoading({
      title: '加载中...',
    })
    this.setData({
      btnState:false,
    });
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: function (ress) {
        wx.login({
          success(res) {
            wx.request({
              url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId') + '&nickName' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密',
              data: {
                storeId: app.globalData.storeId,
                nickName: ress.userInfo.nickName,
                headPortrait: ress.userInfo.avatarUrl,
                sex: '保密',
                xcxOpenId: wx.getStorageSync('openId'),
                unionId: wx.getStorageSync('unionId')
              },
              method: 'POST',
              header: {
                "content-type": "application/json", // 默认
              },
              success: function (rea) {
                if (rea.data.code == 200) {
                  wx.hideLoading({
                    success: (res) => {
                      that.setData({
                        btnState: true,
                        states:false,
                        state:2
                      })
                    },
                  })
                  wx.setStorageSync('nickName', ress.userInfo.nickName);
                  wx.setStorageSync('avatar', ress.userInfo.avatarUrl);
                  that.setData({
                    state: 2
                  });
                  wx.setStorageSync('state', 2);
                }
              }
            })
          }
        })
      },
      fail: function (res) {
        that.setData({
          btnState: true,
        })
        wx.showToast({
          title: '授权失败',
          icon: 'none',
          duration: 1500,
        })
      }
    })
  },
  register() {
    wx.showLoading({
        title: '加载中...',
    });
    let that = this;
    wx.login({
        success(res) {
            wx.request({
                url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
                data: {
                    storeId: app.globalData.storeId,
                    code: res.code
                },
                method: 'POST',
                header: {
                    "content-type": "application/json", // 默认
                },
                success: function (rea) {
                    if (rea.data.code == 200) {
                        let states = false;
                        if (!rea.data.result.hasPhone) {
                            that.setData({
                                state: 1
                            });
                            //home.setKey('state', 1);
                           // wx.setStorageSync('state', 1);
                        } else if (!rea.data.result.hasNickName) {
                            states = true;
                            that.setData({
                                state: 0
                            });
                            //home.setKey('state', 0);
                            //wx.setStorageSync('state', 0);
                        }
                        home.setKey('subscribeTencent', rea.data.result.subscribeTencent);
                        home.setKey('hasNickName', rea.data.result.hasNickName);
                        home.setKey('hasPhone', rea.data.result.hasPhone);
                        home.setKey('userId', rea.data.result.member.id);
                        home.setKey('phone', rea.data.result.member.phone);
                        home.setKey('avatar', rea.data.result.member.avatarUrl);
                        home.setKey('status', rea.data.result.member.status);
                        home.setKey('discount', rea.data.result.member.discount);
                        home.setKey('nickName', rea.data.result.member.nickName);
                        home.setKey('openId', rea.data.result.member.xcxOpenId);
                        home.setKey('unionId', rea.data.result.member.unionId);
                        let states1 = false;
                        if (rea.data.result.hasPhone && rea.data.result.hasNickName) {
                            states1 = !rea.data.result.subscribeTencent;
                            that.setData({
                                state: 2
                            });
                            home.setKey('state', 2);
                            wx.setStorageSync('state', 2);
                            that.getUserInfos();
                        }
                        that.setData({
                            states: states,
                            states1: states1,
                        })
                        wx.hideLoading({
                            success: (res) => {

                            },
                        })
                    } else {
                        home.wxMessage(rea.data.message, 'none');
                    }
                }
            })
        }
    })
},
  getPhoneNumber(e) {
    console.log(e.detail);
    wx.showLoading({
      title: '加载中...',
    });
    this.setData({
      btnState1:false,
    })
    if (e.detail.code == undefined) {
      wx.showToast({
        title: '请授权获取手机号',
        icon: 'none',
        duration: 1500,
      })
      wx.setStorageSync('state', 1);
      this.setData({
        btnState1:true,
      })
      return false;
    }
    let that = this;
    wx.request({
      url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/getPhone?storeId=' + app.globalData.storeId + '&code=' + e.detail.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId'),
      data: {
        storeId: app.globalData.storeId,
        code: e.detail.code,
        xcxOpenId:wx.getStorageSync('openId'),
        unionId:wx.getStorageSync('unionId')
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.hideLoading({
            success: (res) => {
              that.setData({
                btnState1: true,
              });
            },
          })
          wx.setStorageSync('phone', res.data.result.phone);
          wx.setStorageSync('userId', res.data.result.id);
          let state = 2;
          
          if (!wx.getStorageSync('hasNickName')) {
            state = 0;
          }
          
          that.setData({
            state: state
          });
          wx.setStorageSync('state', state);
        } else {
          wx.showToast({
            title: '获取失败',
            icon: 'none',
            duration: 1500,
          })
        }
      }
    })
  },
  onClose1() {
    this.setData({
        states: false,
    })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().setData({
      show3:true,
      show1:false,
      show2:false,
      show4:false,
      show5:false,
    })
    this.setData({
      allGroup:[],
      checkedAll:false,
      money:0,
      goodsMoney:0,
      projectMoney:0,
      listData:[],
      projectData:[],
      goodsData:[],
      checkedGoodsData:[],
      checkedProjectData:[],
      userId:home.getKey('userId')
    });
    if (home.getKey('userId') != '') {
      this.getCommodityCar();
    } else {
      this.setData({show6:true});
    }
    if (home.getKey('state') == 1) {
      this.getTabBar().setData({
        state: 1
      });
    } else if (home.getKey('state') == 2) {
      this.getTabBar().setData({
        state: 2
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})